package ru.belokuriha_online.resort_hotels_belokuriha;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.*;
import android.net.*;
import android.widget.*;
import java.util.*;
import android.content.DialogInterface.OnClickListener;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.drawable.TransitionDrawable;
import android.view.Menu;
import com.google.android.gms.ads.*; //vrem


public class MainActivity extends Activity {

	final int TASK_CODE = 1;
	public final static int STATUS_START = 100; 
	public final static int STATUS_FINISH = 200;
	public final static int STATUS_QUERY = 300;

	public final static String PARAM_RUNS = "runs"; 
	public final static String PARAM_TASK = "task"; 
	public final static String PARAM_PINTENT = "pendingIntent";
	public final static String PARAM_RESULT = "result";
	public final static String PARAM_STATUS = "status";




	Boolean spchbload;
	Boolean spchberror;
	Boolean chbpach;
	String spprisepath;
	public String listvid;
	public String spprisepathfull;
	public ProgressDialog pd;
	int pdshow = 0;
	int cract = 0;
	PendingIntent pi; 
	Intent intent;	
	public static File EDIR = Environment.getExternalStorageDirectory();	
	Integer flagdata;
	String filesanatoriesPath;
	public ListView mlist;
	public GridView grid;
	
	PicTextAdapter gridAdapter;
	public	ArrayList<String> listm;
	public	ArrayList<String> listd;
	public ArrayAdapter<String> listmadapter;
	public ArrayAdapter<String> listdadapter;
	SharedPreferences sp;
	View PullHeader1;
	Intent intentrload;
	String aliassan;
	ArrayList<Map<String, Object>> griddata;
	Map<String, Object> mgv;
	ImageView grid_im;
	Bitmap appdri;
	int size1 = 5;
	int sizes,sizesg;
	LinearLayout Lvgrid;
	TextView tgrid_im;
	int Idg,Idgt;
	int FlagOnlain;
	DisplayMetrics dm1;

	private CharSequence[] spisokdopmenu;
	AlertDialog.Builder dialogdopmenu;
	String pricenomediafull;
	HttpURLConnection urlConnectiond;
	HttpURLConnection urlConnectiondpxml;
	XmlPullParser parser, parserpxml;
	InputStream xmlfile, xmlfilepxml;
	String tmp, tmp_stag,tmp_etag,tmp_text_tag,tmp_atag;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		spisokdopmenu = getResources().getTextArray(R.array.dopmenumain);
		sp = PreferenceManager.getDefaultSharedPreferences(this); 
		
		spchbload = sp.getBoolean("chbload", true);
		spchberror = sp.getBoolean("chberror", false);
		chbpach = sp.getBoolean("chbpach", false);
		listvid = sp.getString("vid_san", "2");
		FlagOnlain = 0;
		tmp = "";
		tmp_stag = "";
		tmp_etag = "";
		tmp_text_tag = "";
		tmp_atag = "";
		mlist = (ListView) findViewById(R.id.list);
		grid = (GridView) findViewById(R.id.gridView);
		
		dm1 = new DisplayMetrics();
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inTargetDensity = dm1.densityDpi;
		
		appdri = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher,null);
		
		sizes = (int) Math.round(appdri.getWidth()*1.3);
		sizesg = (int) Math.round(appdri.getWidth());
		
		 
		
		
		if (listvid.equals("1")) {
			mlist.setVisibility(View.VISIBLE);
			grid.setVisibility(View.GONE);			
		} else {
			mlist.setVisibility(View.GONE);
			grid.setVisibility(View.VISIBLE);
			grid.setColumnWidth(sizesg*3);
					
		}
		
				if (chbpach == true) {
					spprisepath =  sp.getString("prisepath", EDIR + File.separator + getString(R.string.dir_price));
				} 
				else {
					spprisepath = EDIR + File.separator + getString(R.string.dir_price);	
				}
		
		
				spprisepathfull = spprisepath+File.separator+getString(R.string.app_price);
				pricenomediafull = spprisepath+File.separator+getString(R.string.app_nomedia);
				
				try {
		
					File flprice = new File(spprisepathfull);
					flprice.getParentFile().mkdirs();
					if	(flprice.getParentFile().isDirectory()) {
		
					}
					else {
						spprisepathfull = EDIR + File.separator + getString(R.string.dir_price)+File.separator+getString(R.string.app_price);	
						pricenomediafull = EDIR + File.separator + getString(R.string.dir_price)+File.separator+getString(R.string.app_nomedia);
					}
		
				} catch (Exception e) {
					spprisepathfull = EDIR + File.separator + getString(R.string.dir_price)+File.separator+getString(R.string.app_price);	
					pricenomediafull = EDIR + File.separator + getString(R.string.dir_price)+File.separator+getString(R.string.app_nomedia);
				}
		
				nomediapfos(pricenomediafull);
				
		
		pd = new ProgressDialog(this); 

		///
		openlist(); 

		LinearLayout panell = (LinearLayout) findViewById(R.id.panel1);
		LayoutInflater panellInflater = getLayoutInflater();
		View panellorg = panellInflater.inflate(R.layout.panel, panell, true);
		
		LinearLayout reklama = (LinearLayout) findViewById(R.id.reklamagoo1);
		LayoutInflater reklamaInflater = getLayoutInflater();
		try {
			View reklamaorg = reklamaInflater.inflate(R.layout.reklamagoo, reklama, true);
			AdView adView = (AdView)reklamaorg.findViewById(R.id.adView); //vrem
			AdRequest adRequest = new AdRequest.Builder().build();
			adView.loadAd(adRequest); //vrem
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		
		
		final ImageView lingr =(ImageView) findViewById(R.id.LGrid);

		if (listvid.equals("1")) {
			lingr.setImageResource(R.drawable.grid);
		} else {
			lingr.setImageResource(R.drawable.list);
		}

		lingr.setOnClickListener(new View.OnClickListener() {				
			public void onClick(View v) {

				try {

					if (listvid.equals("1")) {
						listvid = "2";

					} else {
						listvid = "1";

					}

					Editor edsp = sp.edit();
					edsp.putString("vid_san", listvid);
					edsp.commit();
					mlist = (ListView) findViewById(R.id.list);
					grid = (GridView) findViewById(R.id.gridView);
					if (listvid.equals("1")) {
						lingr.setImageResource(R.drawable.grid);						
						mlist.setVisibility(View.VISIBLE);
						grid.setVisibility(View.GONE);
						mlist.setAdapter(listmadapter);
					}
					if (listvid.equals("2")) {
						lingr.setImageResource(R.drawable.list);
						mlist.setVisibility(View.GONE);

						
						
						grid.setVisibility(View.VISIBLE);						
						grid.setColumnWidth(sizesg*3);
						grid.setAdapter(gridAdapter);
					}

				} catch (Exception e) {

				}
			}	
		});

		final ImageButton zv1 =(ImageButton) panellorg.findViewById(R.id.imageButton1);
		zv1.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable TelfTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_telef);	
			public void onClick(View v) {

				try {			
					zv1.setImageDrawable(TelfTransition);
					TelfTransition.startTransition(1000);
					String stel = getString(R.string.telefonmob);
					Intent diallintent = new Intent(Intent.ACTION_DIAL,Uri.parse(stel));
					startActivity(diallintent);
				} catch (Exception e) {

				}
			}	
		});

		final ImageButton eml =(ImageButton) panellorg.findViewById(R.id.imageButton2);
		eml.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable EmlTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_eml);
			public void onClick(View v) {
				try {
					eml.setImageDrawable(EmlTransition);
					EmlTransition.startTransition(1000);
					String smail = getString(R.string.email);
					Intent emalintent = new Intent(Intent.ACTION_VIEW,Uri.parse(smail));
					startActivity(emalintent);
				} catch (Exception e) {

				}
			}	
		});
		final ImageButton abt =(ImageButton) panellorg.findViewById(R.id.imageButton4);
		abt.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable AboutTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_about);
			public void onClick(View v) {
				try {
					abt.setImageDrawable(AboutTransition);
					AboutTransition.startTransition(1000);
					Intent intentab = new Intent(getApplicationContext(), About.class);
					intentab.putExtra("spprisepath", spprisepath);
					intentab.putExtra("FlagOnlain", FlagOnlain);
					startActivityForResult(intentab,0);
				} catch (Exception e) {

				}
			}	
		});
		final ImageButton brouz =(ImageButton) panellorg.findViewById(R.id.imageButton5);
		brouz.setVisibility(View.GONE);
		/*brouz.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable BrTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_browser);
			public void onClick(View v) {
				try {
					brouz.setImageDrawable(BrTransition);
					BrTransition.startTransition(1000);
					String sweb = getString(R.string.web);
					Intent brouzintent = new Intent(Intent.ACTION_VIEW,Uri.parse(sweb));
					startActivity(brouzintent);
				} catch (Exception e) {

				}
			}	
		});	
		*/
		final ImageButton favoritsActiv =(ImageButton) panellorg.findViewById(R.id.imageButtonfavoritsactiv);
		favoritsActiv.setVisibility(View.VISIBLE); 
		favoritsActiv.setOnClickListener(new View.OnClickListener() {
		TransitionDrawable favTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_favorits);	
			public void onClick(View v) {
				try {
					favoritsActiv.setImageDrawable(favTransition);
					favTransition.startTransition(1000);
					Intent intentfavoris = new Intent(getApplicationContext(), Favorits.class);
					intentfavoris.putExtra("spprisepath", spprisepath);
					intentfavoris.putExtra("spprisepathfull", spprisepathfull);
					intentfavoris.putExtra("FlagOnlain", FlagOnlain);
					startActivityForResult(intentfavoris,3);
					
				} catch (Exception e) {

				}

			}	
		});

		final ImageButton homes =(ImageButton) panellorg.findViewById(R.id.imageButton3);
		homes.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable HomTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_hom);
			public void onClick(View v) {
				try {
					homes.setImageDrawable(HomTransition);
					HomTransition.startTransition(1000);
					mlist = (ListView) findViewById(R.id.list);
					mlist.setAdapter(listmadapter);
					grid = (GridView) findViewById(R.id.gridView);
					grid.setAdapter(gridAdapter);
				} catch (Exception e) {

				}
			}	
		});
		homes.setOnLongClickListener(new View.OnLongClickListener() {
			TransitionDrawable HomTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_hom);	
			@Override
			public boolean onLongClick(View v) {
				homes.setImageDrawable(HomTransition);
				HomTransition.startTransition(1000);
					Dopmenu();
				return false;
			}
		});

		final ImageButton srav =(ImageButton) panellorg.findViewById(R.id.imageButtonsrav);
		srav.setOnClickListener(new View.OnClickListener() {
			TransitionDrawable sravTransition = (TransitionDrawable)getApplicationContext().getResources().getDrawable(R.drawable.transition_compare);
			public void onClick(View v) {
				try {
					srav.setImageDrawable(sravTransition);
					sravTransition.startTransition(1000);
					Intent intentsea = new Intent(getApplicationContext(), Sravneniye.class);
					intentsea.putExtra("spprisepath", spprisepath);
					intentsea.putExtra("spprisepathfull", spprisepathfull);
					intentsea.putExtra("FlagOnlain", FlagOnlain);
					Integer flags_srav = 0;
					intentsea.putExtra("flags_srav", flags_srav);
					if ((griddata.size() > 0) && (listm.size() > 0)) {
					startActivityForResult(intentsea,3);
					}
				} catch (Exception e) {

				}
			}	
		});
		
		final ImageView Brf =(ImageView) findViewById(R.id.imageViewB);
		Brf.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
				/*	Intent intentsea = new Intent(getApplicationContext(), Seachprice.class);
					intentsea.putExtra("spprisepath", spprisepath);
					intentsea.putExtra("spprisepathfull", spprisepathfull);
					intentsea.putExtra("FlagOnlain", FlagOnlain);
					if ((griddata.size() > 0) && (listm.size() > 0)) {
					startActivityForResult(intentsea,3);
					}
				*/
					/*Intent intentsea = new Intent(getApplicationContext(), Favorits.class);
					intentsea.putExtra("spprisepath", spprisepath);
					intentsea.putExtra("spprisepathfull", spprisepathfull);
					intentsea.putExtra("FlagOnlain", FlagOnlain);
					//if ((griddata.size() > 0) && (listm.size() > 0)) {
						startActivityForResult(intentsea,3);
					//}
					*/	
						String sweb = getString(R.string.web);
						Intent brouzintent = new Intent(Intent.ACTION_VIEW,Uri.parse(sweb));
						startActivity(brouzintent);
						
				} catch (Exception e) {

				}
			}	
		});




		///

	}
	//
	public void nomediapfos(String pricenomediafull) {
		
		File flnomedia = new File(pricenomediafull);
		flnomedia.getParentFile().mkdirs();
		if	(flnomedia.getParentFile().isDirectory()) {

		}
	FileOutputStream fosnomedia = null;
		try {
			fosnomedia = new FileOutputStream(flnomedia);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			fosnomedia.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//
	public void openlist() {
	
		try {
			mlist = (ListView) findViewById(R.id.list);
			grid = (GridView) findViewById(R.id.gridView);

			listm = new ArrayList<String>();
			listd = new ArrayList<String>();

		} catch (Exception e) {

		}

		griddata =  new ArrayList<Map<String, Object>>();

		try { 
			//
			
			//
			
			XmlPullParserFactory parserpull = XmlPullParserFactory.newInstance();
			parserpull.setValidating(false);
			parser = parserpull.newPullParser();
			File xmlfilesanatories = new File(spprisepathfull);
			xmlfile = new FileInputStream(xmlfilesanatories);
			parser.setInput(xmlfile, null);
			
			while (parser.getEventType()!= XmlPullParser.END_DOCUMENT) {
				
// �������� xml ����� ������
if (spchberror == true) {
	
			     switch (parser.getEventType()) { 
		           // ������ ��������� 
		           case XmlPullParser.START_DOCUMENT: 		              
		             break; 
		           // ������ ���� 
		           case XmlPullParser.START_TAG: 
		        	   tmp_stag = "";		       		
		        	   tmp_stag = "START_TAG: name  " + parser.getName() 
		                 + ", depth  " + parser.getDepth() + ", attrCount  " 
		                 + parser.getAttributeCount(); 
		             tmp = ""; 
		             for (int i = 0; i < parser.getAttributeCount(); i++) { 
		               tmp = tmp + parser.getAttributeName(i) + "  " 
		                   + parser.getAttributeValue(i) + ", "; 
		             } 
		             if (!TextUtils.isEmpty(tmp)) 
		            	 tmp_atag = "Attributes: " + tmp; 
		             break; 
		           // ����� ���� 
		           case XmlPullParser.END_TAG: 
		        	  tmp_etag = "END_TAG: name  " + parser.getName(); 
		             break; 
		           // ���������� ���� 
		           case XmlPullParser.TEXT:
		        	 tmp_text_tag = "text  " + parser.getText(); 
		             break; 
		            default: 
		              break; 
		            } 				
}				
// �������� xml ����� �����				
				
				if (parser.getEventType() == XmlPullParser.START_TAG
						&& parser.getName().equals("sanatori") 
						&& parser.getDepth() == 2) {
					mgv = new HashMap<String, Object>();
					listm.add(parser.getAttributeValue(0));
					listd.add(parser.getAttributeValue(1));



					aliassan = parser.getAttributeValue(1);
					if (aliassan == null) {
						aliassan = "";
					}else {
						aliassan = parser.getAttributeValue(1);	
					}

					mgv.put("grt", parser.getAttributeValue(0));

					String sanicon = parser.getAttributeValue(2);
					if (sanicon == null) {
						sanicon = ""; 
					}
					if (!sanicon.equals("")) {
						String filesaniconPath = "";
						if (FlagOnlain == 0) {
							filesaniconPath = spprisepath+File.separator + sanicon;
						} else
						{
							filesaniconPath = spprisepath + sanicon;	
						}
						mgv.put("gri", filesaniconPath);
						mgv.put("gric", sanicon);
						griddata.add(mgv);


					} else {
						mgv.put("gri", R.drawable.resort);
						mgv.put("gric", sanicon);
						griddata.add(mgv);
					}



				}
				
				////*
				parser.next();
			}
			xmlfile.close();
			///\\\   

			////*



			listmadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, listm);
			listdadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, listd);
			listmadapter.notifyDataSetChanged();
			mlist.setAdapter(listmadapter);
			
			
			gridAdapter = new PicTextAdapter(getApplicationContext(), griddata, sizes);

			
			gridAdapter.notifyDataSetChanged();
			
			grid.setAdapter(gridAdapter);
			grid.setOnItemClickListener (new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

					////
					try {
						Intent intent = new Intent(getApplicationContext(),Mainprice.class);
						String sanatori_name = listmadapter.getItem(position);
						String idd_name = listdadapter.getItem(position);							
						intent.putExtra("san_name", sanatori_name);
						intent.putExtra("id_name", idd_name);
						intent.putExtra("spprisepath", spprisepath);
						intent.putExtra("spprisepathfull", spprisepathfull);
						intent.putExtra("FlagOnlain", FlagOnlain);
						Integer flags_srav = 0;
						intent.putExtra("flags_srav", flags_srav);
						startActivityForResult(intent,0);
					} catch (Exception e) {

					}
					
					////	

				}
			}  );




			////*



			//
			mlist.setOnItemClickListener (new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

					////
					try {
						Intent intent = new Intent(getApplicationContext(),Mainprice.class);
						String sanatori_name = listmadapter.getItem(position);
						String idd_name = listdadapter.getItem(position);
						intent.putExtra("san_name", sanatori_name);
						intent.putExtra("id_name", idd_name);
						intent.putExtra("spprisepath", spprisepath);
						intent.putExtra("spprisepathfull", spprisepathfull);
						intent.putExtra("FlagOnlain", FlagOnlain);
						Integer flags_srav = 0;
						intent.putExtra("flags_srav", flags_srav);
						startActivityForResult(intent,0);
					} catch (Exception e) {

					}
					////	

				}
			}  );
			//	
			///\\\

		}
		catch (Throwable terror) {

			if (spchberror == true) {
				Toast.makeText(getApplicationContext(),getString(R.string.error_loadxml)+": \n" + terror.toString(),Toast.LENGTH_LONG ).show();
			}
			if (FlagOnlain == 0) {
				File flprices = new File(spprisepathfull);
				flprices.getParentFile().mkdirs();
				if	((flprices.getParentFile().isDirectory()) & (!flprices.exists())) {
					spchbload = false;
					Qloadprice(0);	
				}
			} else 
			{
				NotInet();
			}
			
		}

		
	}



	@Override 
	protected void onDestroy() {
		super.onDestroy();
		System.gc();
	}

	protected void onRestoreInstanceState(Bundle savedInstanceState) { 

		super.onRestoreInstanceState(savedInstanceState); 
		pdshow = savedInstanceState.getInt("pdshow");
		cract = savedInstanceState.getInt("cract"); 
		spchbload = savedInstanceState.getBoolean("spchbload");
		spchberror = savedInstanceState.getBoolean("spchberror");
		chbpach = savedInstanceState.getBoolean("chbpach");
		spprisepath = savedInstanceState.getString("spprisepath");
		spprisepathfull = savedInstanceState.getString("spprisepathfull");
		FlagOnlain = savedInstanceState.getInt("FlagOnlain");
		
		listvid = savedInstanceState.getString("listvid");

		// 

	} 

	protected void onSaveInstanceState(Bundle outState) { 
		super.onSaveInstanceState(outState); 
		outState.putInt("pdshow", pdshow);
		outState.putInt("cract", cract);
		outState.putBoolean("spchbload",spchbload);
		outState.putBoolean("spchberror",spchberror);
		outState.putBoolean("chbpach",chbpach);
		outState.putString("spprisepath",spprisepath);
		outState.putString("spprisepathfull",spprisepathfull);
		outState.putInt("FlagOnlain", FlagOnlain);
		outState.putString("listvid",listvid);
		//
	} 
	protected void onResume() { 

		super.onResume();

		if (pdshow == 1) {
			ProgressD();
		}
		if (spchbload == true) {

			if (cract == 0) {				
				Startpserves(0);				
			}
		}

		


	} 





	public boolean onCreateOptionsMenu(Menu menu) { 

		getMenuInflater().inflate(R.menu.pmenu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) { 
		if (FlagOnlain == 0) {
			menu.findItem(R.id.loaditem1).setVisible(true);
			menu.findItem(R.id.loaditem1).setEnabled(true);
			} else
			{			
			menu.findItem(R.id.loaditem1).setEnabled(false);
			menu.findItem(R.id.loaditem1).setVisible(false);
			}
			menu.findItem(R.id.pitem2).setEnabled(true);
			menu.findItem(R.id.abitem3).setEnabled(true);	
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) { 

		case R.id.loaditem1: 

			Qloadprice(1);
			break; 

		case R.id.pitem2:

			try {
				Intent Preferintent = new Intent(getApplicationContext(),PreferActivity.class);
				Preferintent.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(Preferintent, 0);
			} catch (Exception e) {

			}
			break; 
		case R.id.abitem3: 

			try {
				Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
				intentapp.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(intentapp, 0);
			} catch (Exception e) {

			}
			break;
		}       


		return super.onOptionsItemSelected(item); 

	} 


	public void Startpserves(int p_runs) {
		cract=1;
		try {
			if (FlagOnlain == 0) {
			intent = new Intent(getApplicationContext(), MyAmsService.class); 

			pi = createPendingResult(TASK_CODE, intent, 0);
			intent.putExtra(PARAM_RUNS, p_runs)
			.putExtra("spprisepath", spprisepath)
			.putExtra("spprisepathfull", spprisepathfull)
			.putExtra(PARAM_PINTENT, pi);			
			startService(intent); 
			}
		} catch (Exception e) {

		}

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);


		if (resultCode == STATUS_START) { 
		} 

		if (resultCode ==  STATUS_FINISH) { 
			int result = data.getIntExtra(PARAM_RESULT, 0);	      	 
			
			
			if (result == 1) { 
				pd.hide();
				pdshow = 0;
				openlist();
				Toast.makeText(this,getString(R.string.okload),Toast.LENGTH_LONG ).show();
			} 
			if (result == 2) {
				pd.hide();
				pdshow = 0;
			  if (FlagOnlain == 0) {
				NotInet();
			  }
				System.gc();
			} 

		}


		if (resultCode ==  STATUS_QUERY) {
			int result = data.getIntExtra(PARAM_RESULT, 0);	
			//openlist();
			if (FlagOnlain == 0) {
			Queryloadprice(); 
			}
			
			
		}

		if (resultCode ==  7) { 

			ProgressD();
			pdshow = 1;
			Startpserves(1); 

		}

		if (resultCode ==  5) {
			try {
				openOptionsMenu();
			} catch (Exception e) {

			}
		}
		if (resultCode ==  9) {
			try {
				Intent Preferintent = new Intent(getApplicationContext(),PreferActivity.class);
				Preferintent.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(Preferintent,0);
			} catch (Exception e) {

			}
		}
		if (resultCode ==  10) {	
			try {
				Intent intentapp = new Intent(getApplicationContext(), Aboutapp.class);
				intentapp.putExtra("FlagOnlain", FlagOnlain);
				startActivityForResult(intentapp,0);	
			} catch (Exception e) {

			}
		}

	}
	protected void ProgressD() {
		
		pd.setCancelable(false);

		pd.setMessage(getString(R.string.pdm_app));	   
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setButton(Dialog.BUTTON_NEGATIVE,getString(R.string.pdbutton_neg), new OnClickListener() { 

			public void onClick(DialogInterface dialog, int which) { 
				try {	            		 

					stopService(new Intent(getApplicationContext(), MyAmsService.class)); 

					pd.hide();
					pdshow = 0;	
					openlist();
				} catch (Exception e) {

				}

			} 

		}); 

		pd.show();
		
	}    
	protected void Queryloadprice() {
		AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
		builder2.setTitle(R.string.lqt_app);
		builder2.setMessage(R.string.lqm_app);
		builder2.setNegativeButton(R.string.qn_app, null);
		builder2.setPositiveButton(R.string.qy_app, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				ProgressD();
				pdshow = 1;
				Startpserves(1);
				
			}
		}).create().show();	
		
	}
	protected void NotInet() {
		AlertDialog.Builder builder4 = new AlertDialog.Builder(this);
		builder4.setTitle(R.string.tit_connect);
		builder4.setMessage(R.string.mes_connect);
		builder4.setNeutralButton(R.string.botclose, null);
		builder4.create().show();	
	}
	protected void Qloadprice(Integer rejim) {
		AlertDialog.Builder builder3 = new AlertDialog.Builder(this);
		builder3.setTitle(R.string.lt_app);
		if (rejim == 0) {
			builder3.setMessage(R.string.lmm_app);	
		}
		else {
			builder3.setMessage(R.string.lm_app);
		}
		builder3.setNegativeButton(R.string.qn_app, null);
		builder3.setPositiveButton(R.string.qy_app, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				
				ProgressD();
				pdshow = 1;
				Startpserves(1);
				
				
			}
		}).create().show();	
	} 
	public void Dopmenu() {
		dialogdopmenu = new AlertDialog.Builder(this);
		dialogdopmenu.setTitle("");		
		dialogdopmenu.setItems(spisokdopmenu, 
				new DialogInterface.OnClickListener() {					
			@Override
			public void onClick(DialogInterface dialog, int item) {
				switch (item) { 

				case 0:
					try{
						openOptionsMenu();	

					} catch (Exception e) {

					}
					break;
					
				case 1:

					try {
						quitapp();
					} catch (Exception e) {

					}
					break; 

				}       					
			}
		}				
				).create().show();


	}
	public void quitapp() {
		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setTitle(R.string.qt_app);
		builder1.setMessage(R.string.qm_app);
		builder1.setNegativeButton(R.string.qn_app, null);
		builder1.setNeutralButton(R.string.appocencam, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				try {
					Intent appocenca = new Intent(Intent.ACTION_VIEW);
					appocenca.setData(Uri.parse(getString(R.string.appocencauri)));
					startActivity(appocenca);
				} catch (Exception e) {
					Intent appocencabr = new Intent(Intent.ACTION_VIEW,Uri.parse(getString(R.string.appocencauribrouse)));
					startActivity(appocencabr);
				}
			}
		});
		builder1.setPositiveButton(R.string.qy_app, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				MainActivity.super.onBackPressed();
				try {

					stopService(new Intent(getApplicationContext(), MyAmsService.class)); 

				} catch (Exception e) {

				}
				System.gc();
				MainActivity.super.onDestroy();
				System.gc();
			}
		});
		builder1.create().show();	
	}
	//	    
	/////
	@Override
	public void onBackPressed() {
		quitapp();
	}
	/////

}
